package com.zxj.common.security.interceptor;

import cn.hutool.core.util.StrUtil;
import com.zxj.common.core.contains.Constants;
import com.zxj.common.core.contains.HttpConstants;
import com.zxj.common.core.utils.ThreadLocalUtil;
import com.zxj.common.security.service.TokenService;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.ModelAndView;

/**
 * token拦截器
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class TokenInterceptor implements HandlerInterceptor {

    private final TokenService tokenService;

    @Value("${oj.jwt.token.secret}")
    private String secret;  //从哪个服务的配置文件中读取，取决于这个bean对象交给了哪个服务的spring容器进行管理。

    /**
     * 从网关走到这里, 说明token验证通过, 这里拦截是用于判断是否要延长token的过期时间的
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("TokenInterceptor preHandle 拦截请求: {}", request.getRequestURI());

        // 1. 从请求头中获取token
        String token = this.getToken(request);
        // 2. 判断token是否为空
        if (StrUtil.isEmpty(token)) {
            return true;
        }
        // 3. 判断token是否需要延长
        Claims claims = tokenService.getClaimsFromToken(token, secret);
        tokenService.extendToken(claims);


        // 4. 保存用户信息到上下文
        ThreadLocalUtil.setUserId(tokenService.getUserId(claims));
        ThreadLocalUtil.setUserKey(tokenService.getUserKey(claims));

        // 5. 返回true, 继续执行
        return true;
    }

    /**
     * 请求结束后, 移除用户信息
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        ThreadLocalUtil.remove();
    }

    /**
     * 从请求头中获取token
     * @param request 请求
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(HttpConstants.AUTHENTICATION);
        if (StrUtil.isNotEmpty(token) && token.startsWith(HttpConstants.PREFIX)) {
            token = token.replaceFirst(HttpConstants.PREFIX, "");
        }
        return token;
    }
}
